import {
  emtpyToUndefined,
  isNumber,
  isArray,
  isNull,
  isUndefined,
  isInteger,
  isString,
  isEmpty,
  PagedList,
  PageParams,
  StringIndexer,
  toString,
  isBoolean,
} from "mmb";
import * as activitypb from "../grpc-client/service/activity_pb";
import * as sharedpb from "../grpc-client/shared/message_pb";
import {
  getBgsActivityOpSafely,
  getMetadata,
  getOptionsOfLight,
  wrapperGrpcError,
} from "../grpc-client/grpcAdapter";
import GrpcErrCode from "../grpc-client/grpcErrCode";
import {
  productAttributeDefPbToObject,
  pbTimestampToJs,
  jsTimestampToPb,
  checkIn1PbToObject,
  checkIn1ObjectToPb,
  lottery1PbToObject,
  lottery1ObjectToPb,
} from "./helper";
import {
  ActivityIntroItemType,
  ActivityIntroItem,
  CheckIn1,
  Lottery1,
  ActivityOfB,
  ActivityOfStore,
  ActivityOfS,
  ActivityOfU2CWithStatAndOwnerInfo,
  ActivityProductIsShow,
  ActivityProductWithSku,
  ActivityProductWithAttributeDefAndSku,
  ActivitySku,
  ActivityConsignment,
  ActivityConsignmentBonusSetting,
  ActivityItemOfBWithStat,
  ActivityItemOfStoreWithStat,
  ActivityItemOfSWithStat,
  ActivityItemOfU2BWithStatAndBrandInfo,
  ActivityItemOfU2CWithStatAndOwnerInfo,
  CreateActivityOfBParams,
  UpdateActivityOfBParams,
  PublishActivityOfBParams,
  CreateActivityOfStoreParams,
  UpdateActivityOfStoreParams,
  PublishActivityOfStoreParams,
  CreateActivityOfSParams,
  UpdateActivityOfSParams,
  GetActivityOfSByParentIDAndSpokesmanIDParams,
  UpdateActivityOfBProcessStatusParams,
  UpdateActivityOfStoreProcessStatusParams,
  UpdateActivityOfSProcessStatusParams,
  PublishActivityOfSParams,
  GetActivityOfU2CWithStatAndOwnerInfoForUserParams,
  ProductAttributeDefExt,
  ProductAttributeDef,
  TimeRange,
} from "./declareTypes";
import ActivityProcessStatus from "../bg-enums/activityProcessStatus";
import ActivitySaleMode, {
  isActivitySaleMode,
} from "../bg-enums/activitySaleMode";
import ActivityQualifyType from "../bg-enums/activityQualifyType";
import ActivityOwner from "../bg-enums/activityOwner";
import ActivityType, {
  isActivityType,
  checkIsAsFeature,
  checkNeedTypeInfo,
  checkCanEndorse,
} from "../bg-enums/activityType";
import DeliveryMode, { isDeliveryMode } from "../bg-enums/deliveryMode";

/****************************************************************************************/
/*                                   activity entity                                    */
/****************************************************************************************/

const activityOfBPbToObject = (
  pb: activitypb.ActivityOfBEntity
): ActivityOfB => {
  var activityType = pb.getType() as ActivityType;
  var ret: ActivityOfB = {
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: activityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    background: emtpyToUndefined(pb.getBackground()),
    poster: emtpyToUndefined(pb.getPoster()),
    saleMode: pb.getSaleMode() as ActivitySaleMode,
    verifyQualification: pb.getVerifyQualification(),
    qualifyTypes: pb.getQualifyTypesList().map((v) => v as ActivityQualifyType),
    deliveryModes: pb.getDeliveryModesList().map((v) => v as DeliveryMode),
    isUseWarehouseShippingFeeRule: pb.getIsUseWarehouseShippingFeeRule(),
    unifiedShippingFee: emtpyToUndefined(pb.getUnifiedShippingFee()),
    maxiumPurchaseFrequency: emtpyToUndefined(pb.getMaxiumPurchaseFrequency()),
    minimumPurchaseAmount: pb.getMinimumPurchaseAmount(),
    tel: pb.getTel(),
    owner: pb.getOwner() as ActivityOwner,
    inventoryFreezeNo: pb.getInventoryFreezeNo(),
    warehouseIds: pb.getWarehouseIdsList().map((v) => toString(v)),
    activityProductWithSkus: pb
      .getActivityProductWithSkusList()
      .map(activityProductWithSkusPbToObject),
  };

  if (checkCanEndorse(activityType)) {
    ret.consignment = activityConsignmentPbToObject(pb.getConsignment()!);
  }

  if (checkNeedTypeInfo(activityType)) {
    switch (activityType) {
      case ActivityType.CHECK_IN__1:
        ret.checkIn1 = checkIn1PbToObject(pb.getCheckIn1()!);
        break;
      case ActivityType.LOTTERY__1:
        ret.lottery1 = lottery1PbToObject(pb.getLottery1()!);
        break;
      default:
        break;
    }
  }
  return ret;
};

const activityOfStorePbToObject = (
  pb: activitypb.ActivityOfStoreEntity
): ActivityOfStore => {
  var activityType = pb.getType() as ActivityType;
  var ret: ActivityOfStore = {
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    storeId: toString(pb.getStoreId()),
    distributorId: toString(pb.getDistributorId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: activityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    background: emtpyToUndefined(pb.getBackground()),
    poster: emtpyToUndefined(pb.getPoster()),
    saleMode: pb.getSaleMode() as ActivitySaleMode,
    verifyQualification: pb.getVerifyQualification(),
    qualifyTypes: pb.getQualifyTypesList().map((v) => v as ActivityQualifyType),
    maxiumPurchaseFrequency: emtpyToUndefined(pb.getMaxiumPurchaseFrequency()),
    minimumPurchaseAmount: pb.getMinimumPurchaseAmount(),
    tel: pb.getTel(),
    owner: pb.getOwner() as ActivityOwner,
    activityProductWithSkus: pb
      .getActivityProductWithSkusList()
      .map(activityProductWithSkusPbToObject),
  };

  if (checkCanEndorse(activityType)) {
    ret.consignment = activityConsignmentPbToObject(pb.getConsignment()!);
  }
  return ret;
};

const activityOfSPbToObject = (
  pb: activitypb.ActivityOfSEntity
): ActivityOfS => {
  return {
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    background: emtpyToUndefined(pb.getBackground()),
    poster: emtpyToUndefined(pb.getPoster()),
    saleMode: pb.getSaleMode() as ActivitySaleMode,
    verifyQualification: pb.getVerifyQualification(),
    qualifyTypes: pb.getQualifyTypesList().map((v) => v as ActivityQualifyType),
    deliveryModes: pb.getDeliveryModesList().map((v) => v as DeliveryMode),
    spokesmanId: toString(pb.getSpokesmanId()),
    maxiumPurchaseFrequency: emtpyToUndefined(pb.getMaxiumPurchaseFrequency()),
    minimumPurchaseAmount: pb.getMinimumPurchaseAmount(),
    tel: pb.getTel(),
    owner: pb.getOwner() as ActivityOwner,
    rootId: toString(pb.getRootId()),
    parentId: toString(pb.getParentId()),
    activityProductWithSkus: pb
      .getActivityProductWithSkusList()
      .map(activityProductWithSkusPbToObject),
    // consignment: activityConsignmentPbToObject(pb.getConsignment()!),
  };
};

const activityProductWithSkusPbToObject = (
  pb: activitypb.ActivityProductWithSkuEntity
): ActivityProductWithSku => {
  // console.log("pb.getSkusList=>", pb.getSkusList());
  return {
    activityProductId: toString(pb.getId()),
    productId: toString(pb.getProductId()),
    priceMin: pb.getPriceMin(),
    priceMax: pb.getPriceMax(),
    quantity: pb.getQuantity(),
    isShow: pb.getIsShow(),
    skus: pb.getSkusList().map(activitySkuPbToObject),
    // product info
    productName: pb.getProductName(),
    productPics: pb.getProductPicsList(),
  };
};

const activityProductWithAttributeDefAndSkusPbToObject = (
  pb: activitypb.ActivityProductWithAttributeDefAndSkuEntity
): ActivityProductWithAttributeDefAndSku => {
  // console.log("pb.getSkusList=>", pb.getSkusList());
  return {
    activityProductId: toString(pb.getId()),
    productId: toString(pb.getProductId()),
    priceMin: pb.getPriceMin(),
    priceMax: pb.getPriceMax(),
    quantity: pb.getQuantity(),
    isShow: pb.getIsShow(),
    productAttributeDefs: pb
      .getProductAttributeDefsList()
      .map(productAttributeDefPbToObject),
    skus: pb.getSkusList().map(activitySkuPbToObject),
    // product info
    productName: pb.getProductName(),
    productPics: pb.getProductPicsList(),
    productIntro: pb.getProductIntro(),
    productIntroPics: pb.getProductIntroPicsList(),
  };
};

const activitySkuPbToObject = (
  pb: activitypb.ActivitySkuEntity
): ActivitySku => {
  return {
    activitySkuId: toString(pb.getId()),
    productId: toString(pb.getProductId()),
    productSpecId: emtpyToUndefined(toString(pb.getProductSpecId())),
    price: pb.getPrice(),
    maximum: pb.getMaximum(),
    freezeQuantity: pb.getFreezeQuantity(),
    soldedQuantity: pb.getSoldedQuantity(),
    storageKey: pb.getStorageKey(),
    skuName: pb.getSkuName(),
  };
};

const activityConsignmentPbToObject = (
  pb: activitypb.ActivityConsignmentEntity
): ActivityConsignment => {
  return {
    allowHiddenProduct: pb.getAllowHiddenProduct(),
    allowAllSpokesman: pb.getAllowAllSpokesman(),
    specificSpokesmanIds: pb
      .getSpecificSpokesmanIdsList()
      .map((v) => toString(v)),
    consignmentBonusSettings: pb
      .getConsignmentBonusSettingsList()
      .map(activityConsignmentBonusSettingPbToObject),
  };
};

const activityConsignmentBonusSettingPbToObject = (
  pb: activitypb.ActivityConsignmentBonusSettingEntity
): ActivityConsignmentBonusSetting => {
  return {
    productId: toString(pb.getProductId()),
    bonusRate: pb.getBonusRate(),
  };
};

const activitySkuObjectToPb = (o: ActivitySku) => {
  const pb = new activitypb.ActivitySkuEntity();
  // pb.setId(Number(o.activitySkuId))
  pb.setProductId(Number(o.productId));
  if (!isUndefined(o.productSpecId)) {
    pb.setProductSpecId(Number(o.productSpecId));
  }
  pb.setPrice(o.price);
  pb.setMaximum(o.maximum);
  return pb;
};

const activityProductWithSkusObjectToPb = (o: ActivityProductWithSku) => {
  const pb = new activitypb.ActivityProductWithSkuEntity();
  // pb.setId(Number(o.activityProductId))
  pb.setProductId(Number(o.productId));
  pb.setPriceMin(o.priceMin);
  pb.setPriceMax(o.priceMax);
  pb.setQuantity(o.quantity);
  pb.setIsShow(o.isShow);
  pb.setSkusList(o.skus.map(activitySkuObjectToPb));
  return pb;
};

const activityProductIsShowsObjectToPb = (o: ActivityProductIsShow) => {
  const pb = new activitypb.ActivityProductIsShowEntity();
  // pb.setId(Number(o.activityProductId))
  pb.setProductId(Number(o.productId));
  pb.setIsShow(o.isShow);
  return pb;
};

const activityConsignmentObjectToPb = (o: ActivityConsignment) => {
  const pb = new activitypb.ActivityConsignmentEntity();
  pb.setAllowHiddenProduct(o.allowHiddenProduct);
  pb.setAllowAllSpokesman(o.allowAllSpokesman);
  if (!isUndefined(o.specificSpokesmanIds)) {
    pb.setSpecificSpokesmanIdsList(o.specificSpokesmanIds.map(Number));
  }
  if (!isUndefined(o.consignmentBonusSettings)) {
    pb.setConsignmentBonusSettingsList(
      o.consignmentBonusSettings.map(activityConsignmentBonusSettingObjectToPb)
    );
  }
  return pb;
};

const activityConsignmentBonusSettingObjectToPb = (
  o: ActivityConsignmentBonusSetting
) => {
  const pb = new activitypb.ActivityConsignmentBonusSettingEntity();
  pb.setProductId(Number(o.productId));
  pb.setBonusRate(o.bonusRate);
  return pb;
};

const timeRangeObjectToPb = (o: TimeRange) => {
  const pb = new sharedpb.TimeRange();
  pb.setBeginAt(o.beginAt);
  pb.setEndAt(o.endAt);
  return pb;
};

/****************************************************************************************/
/*                                   activity cmd                                       */
/****************************************************************************************/

export const createActivityOfB = async ({
  brandId,
  pubUserId,
  type,
  name,
  intro,
  begined,
  ended,
  timeRanges,
  background,
  checkIn1,
  lottery1,
  saleMode,
  deliveryModes,
  isUseWarehouseShippingFeeRule,
  unifiedShippingFee,
  maxiumPurchaseFrequency,
  minimumPurchaseAmount,
  tel,
  // warehouses
  warehouseIds,
  // productWithSkus
  activityProductWithSkus,
  // consignment
  consignment,
}: CreateActivityOfBParams): Promise<ActivityOfB> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.CreateActivityOfBRequest();

  req.setBrandId(Number(brandId));
  req.setPubUserId(Number(pubUserId));
  req.setType(type);
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  req.setBegined(jsTimestampToPb(begined));
  req.setEnded(jsTimestampToPb(ended));
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  if (!isUndefined(timeRanges)) {
    req.setTimeRangesList(timeRanges.map(timeRangeObjectToPb));
  }
  if (checkNeedTypeInfo(type)) {
    switch (type) {
      case ActivityType.CHECK_IN__1:
        req.setCheckIn1(checkIn1ObjectToPb(checkIn1!));
        break;
      case ActivityType.LOTTERY__1:
        req.setLottery1(lottery1ObjectToPb(lottery1!));
        break;
      default:
        break;
    }
  }
  req.setSaleMode(saleMode);
  req.setDeliveryModesList(deliveryModes);
  req.setIsUseWarehouseShippingFeeRule(isUseWarehouseShippingFeeRule);
  if (!isUndefined(unifiedShippingFee)) {
    req.setUnifiedShippingFee(unifiedShippingFee);
  }
  if (!isUndefined(maxiumPurchaseFrequency)) {
    req.setMaxiumPurchaseFrequency(maxiumPurchaseFrequency);
  }
  req.setMinimumPurchaseAmount(minimumPurchaseAmount);
  req.setTel(tel);
  req.setWarehouseIdsList(warehouseIds.map(Number));
  req.setActivityProductWithSkusList(
    activityProductWithSkus.map(activityProductWithSkusObjectToPb)
  );
  if (!isUndefined(consignment)) {
    req.setConsignment(activityConsignmentObjectToPb(consignment));
  }

  return new Promise((resolve, reject) => {
    cl.createActivityOfB(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          console.log("err=>", err);
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          console.log("err=>", opRet.getMsg());
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfBPbToObject(res.getActivityOfB()!));
      }
    );
  });
};

export const updateActivityOfB = async ({
  activityId,
  type,
  name,
  intro,
  begined,
  ended,
  timeRanges,
  background,
  checkIn1,
  lottery1,
  saleMode,
  deliveryModes,
  isUseWarehouseShippingFeeRule,
  unifiedShippingFee,
  maxiumPurchaseFrequency,
  minimumPurchaseAmount,
  tel,
  // warehouses
  warehouseIds,
  // productWithSkus
  activityProductWithSkus,
  // consignment
  consignment,
}: UpdateActivityOfBParams): Promise<ActivityOfB> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.UpdateActivityOfBRequest();

  req.setId(Number(activityId));
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  req.setBegined(jsTimestampToPb(begined));
  req.setEnded(jsTimestampToPb(ended));
  if (!isUndefined(timeRanges)) {
    req.setTimeRangesList(timeRanges.map(timeRangeObjectToPb));
  }
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  if (checkNeedTypeInfo(type)) {
    switch (type) {
      case ActivityType.CHECK_IN__1:
        req.setCheckIn1(checkIn1ObjectToPb(checkIn1!));
        break;
      case ActivityType.LOTTERY__1:
        req.setLottery1(lottery1ObjectToPb(lottery1!));
        break;
      default:
        break;
    }
  }
  req.setSaleMode(saleMode);
  req.setDeliveryModesList(deliveryModes);
  req.setIsUseWarehouseShippingFeeRule(isUseWarehouseShippingFeeRule);
  if (!isUndefined(unifiedShippingFee)) {
    req.setUnifiedShippingFee(unifiedShippingFee);
  }
  if (!isUndefined(maxiumPurchaseFrequency)) {
    req.setMaxiumPurchaseFrequency(maxiumPurchaseFrequency);
  }
  req.setMinimumPurchaseAmount(minimumPurchaseAmount);
  req.setTel(tel);
  req.setWarehouseIdsList(warehouseIds.map(Number));
  req.setActivityProductWithSkusList(
    activityProductWithSkus.map(activityProductWithSkusObjectToPb)
  );
  if (!isUndefined(consignment)) {
    req.setConsignment(activityConsignmentObjectToPb(consignment));
  }

  return new Promise((resolve, reject) => {
    cl.updateActivityOfB(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfBPbToObject(res.getActivityOfB()!));
      }
    );
  });
};

export const publishActivityOfB = async ({
  activityId,
  userId,
}: PublishActivityOfBParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PublishActivityOfBRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.publishActivityOfB(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(res.getProcessStatus()! as ActivityProcessStatus);
      }
    );
  });
};

export const pauseActivityOfB = async ({
  activityId,
  brandId,
}: UpdateActivityOfBProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PauseActivityRequest();

  req.setId(Number(activityId));
  req.setBrandId(Number(brandId));

  return new Promise((resolve, reject) => {
    cl.pauseActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const resumeActivityOfB = async ({
  activityId,
  brandId,
}: UpdateActivityOfBProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.ResumeActivityRequest();

  req.setId(Number(activityId));
  req.setBrandId(Number(brandId));

  return new Promise((resolve, reject) => {
    cl.resumeActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const createActivityOfStore = async ({
  storeId,
  pubUserId,
  type,
  name,
  intro,
  begined,
  ended,
  timeRanges,
  background,
  saleMode,
  maxiumPurchaseFrequency,
  minimumPurchaseAmount,
  tel,
  // productWithSkus
  activityProductWithSkus,
  // consignment
  consignment,
}: CreateActivityOfStoreParams): Promise<ActivityOfStore> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.CreateActivityOfStoreRequest();

  req.setStoreId(Number(storeId));
  req.setPubUserId(Number(pubUserId));
  req.setType(type);
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  req.setBegined(jsTimestampToPb(begined));
  req.setEnded(jsTimestampToPb(ended));
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  if (!isUndefined(timeRanges)) {
    req.setTimeRangesList(timeRanges.map(timeRangeObjectToPb));
  }
  req.setSaleMode(saleMode);
  if (!isUndefined(maxiumPurchaseFrequency)) {
    req.setMaxiumPurchaseFrequency(maxiumPurchaseFrequency);
  }
  req.setMinimumPurchaseAmount(minimumPurchaseAmount);
  req.setTel(tel);
  req.setActivityProductWithSkusList(
    activityProductWithSkus.map(activityProductWithSkusObjectToPb)
  );
  if (!isUndefined(consignment)) {
    req.setConsignment(activityConsignmentObjectToPb(consignment));
  }

  return new Promise((resolve, reject) => {
    cl.createActivityOfStore(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          console.log("err=>", err);
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          console.log("err=>", opRet.getMsg());
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfStorePbToObject(res.getActivityOfStore()!));
      }
    );
  });
};

export const updateActivityOfStore = async ({
  activityId,
  type,
  name,
  intro,
  begined,
  ended,
  timeRanges,
  background,
  saleMode,
  maxiumPurchaseFrequency,
  minimumPurchaseAmount,
  tel,
  // productWithSkus
  activityProductWithSkus,
  // consignment
  consignment,

  storeId,
}: UpdateActivityOfStoreParams): Promise<ActivityOfStore> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.UpdateActivityOfStoreRequest();

  req.setId(Number(activityId));
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  req.setBegined(jsTimestampToPb(begined));
  req.setEnded(jsTimestampToPb(ended));
  if (!isUndefined(timeRanges)) {
    req.setTimeRangesList(timeRanges.map(timeRangeObjectToPb));
  }
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  req.setSaleMode(saleMode);
  if (!isUndefined(maxiumPurchaseFrequency)) {
    req.setMaxiumPurchaseFrequency(maxiumPurchaseFrequency);
  }
  req.setMinimumPurchaseAmount(minimumPurchaseAmount);
  req.setTel(tel);
  req.setActivityProductWithSkusList(
    activityProductWithSkus.map(activityProductWithSkusObjectToPb)
  );
  if (!isUndefined(consignment)) {
    req.setConsignment(activityConsignmentObjectToPb(consignment));
  }
  req.setStoreId(Number(storeId));

  return new Promise((resolve, reject) => {
    cl.updateActivityOfStore(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfStorePbToObject(res.getActivityOfStore()!));
      }
    );
  });
};

export const publishActivityOfStore = async ({
  activityId,
  userId,
  storeId,
}: PublishActivityOfStoreParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PublishActivityOfStoreRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));
  req.setStoreId(Number(storeId));

  return new Promise((resolve, reject) => {
    cl.publishActivityOfStore(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(res.getProcessStatus()! as ActivityProcessStatus);
      }
    );
  });
};

export const pauseActivityOfStore = async ({
  activityId,
  storeId,
}: UpdateActivityOfStoreProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PauseActivityRequest();

  req.setId(Number(activityId));
  req.setStoreId(Number(storeId));

  return new Promise((resolve, reject) => {
    cl.pauseActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const resumeActivityOfStore = async ({
  activityId,
  storeId,
}: UpdateActivityOfStoreProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.ResumeActivityRequest();

  req.setId(Number(activityId));
  req.setBrandId(Number(storeId));

  return new Promise((resolve, reject) => {
    cl.resumeActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const endorseActivityByS = async (
  activityId: string,
  userId: string
): Promise<ActivityOfS> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.EndorseActivityBySRequest();

  req.setActivityId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.endorseActivityByS(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfSPbToObject(res.getActivityOfS()!));
      }
    );
  });
};

export const createActivityOfS = async ({
  parentId,
  spokesmanId,
  pubUserId,
  name,
  intro,
  background,
  tel,
  // product is_show
  activityProductIsShows,
}: CreateActivityOfSParams): Promise<ActivityOfS> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.CreateActivityOfSRequest();

  req.setParentId(Number(parentId));
  req.setSpokesmanId(Number(spokesmanId));
  req.setPubUserId(Number(pubUserId));
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  req.setTel(tel);
  req.setActivityProductIsShowsList(
    activityProductIsShows.map(activityProductIsShowsObjectToPb)
  );

  return new Promise((resolve, reject) => {
    cl.createActivityOfS(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfSPbToObject(res.getActivityOfS()!));
      }
    );
  });
};

export const updateActivityOfS = async ({
  activityId,
  name,
  intro,
  background,
  tel,
  // product is_show
  activityProductIsShows,
}: UpdateActivityOfSParams): Promise<ActivityOfS> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.UpdateActivityOfSRequest();

  req.setId(Number(activityId));
  req.setName(name);
  req.setIntro(JSON.stringify(intro));
  if (!isUndefined(background)) {
    req.setBackground(background);
  }
  req.setTel(tel);
  req.setActivityProductIsShowsList(
    activityProductIsShows.map(activityProductIsShowsObjectToPb)
  );

  return new Promise((resolve, reject) => {
    cl.updateActivityOfS(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfSPbToObject(res.getActivityOfS()!));
      }
    );
  });
};

export const pauseActivityOfS = async ({
  activityId,
  userId,
}: UpdateActivityOfSProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PauseActivityRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.pauseActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const resumeActivityOfS = async ({
  activityId,
  userId,
}: UpdateActivityOfSProcessStatusParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.ResumeActivityRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.resumeActivity(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(res.getProcessStatus()! as ActivityProcessStatus);
    });
  });
};

export const publishActivityOfS = async ({
  activityId,
  userId,
}: PublishActivityOfSParams): Promise<ActivityProcessStatus> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.PublishActivityOfSRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.publishActivityOfS(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(res.getProcessStatus()! as ActivityProcessStatus);
      }
    );
  });
};

/****************************************************************************************/
/*                                   activity query                                     */
/****************************************************************************************/

export const getActivityOfB = async (
  activityId: string
): Promise<ActivityOfB> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.GetActivityOfBRequest();

  req.setId(Number(activityId));

  return new Promise((resolve, reject) => {
    cl.getActivityOfB(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(activityOfBPbToObject(res.getActivityOfB()!));
    });
  });
};

export const getActivityOfBAsFeature = async (
  brandId: string,
  type: ActivityType
): Promise<ActivityOfB | undefined> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.GetActivityOfBAsFeatureRequest();

  req.setBrandId(Number(brandId));
  req.setType(type);

  return new Promise((resolve, reject) => {
    cl.getActivityOfBAsFeature(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        console.log("opRet=>", opRet.getSuccess(), opRet.getCode());
        if (!opRet.getSuccess()) {
          if (opRet.getCode() === GrpcErrCode.NOT_FOUND) {
            console.log("asdf");
            resolve(undefined);
            return;
          } else {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
        }
        resolve(activityOfBPbToObject(res.getActivityOfB()!));
      }
    );
  });
};

export const getActivityOfStore = async (
  activityId: string,
  storeId: string
): Promise<ActivityOfStore> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.GetActivityOfStoreRequest();

  req.setId(Number(activityId));
  req.setStoreId(Number(storeId));

  return new Promise((resolve, reject) => {
    cl.getActivityOfStore(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        resolve(activityOfStorePbToObject(res.getActivityOfStore()!));
      }
    );
  });
};

export const getActivityOfS = async (
  activityId: string
): Promise<ActivityOfS> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.GetActivityOfSRequest();

  req.setId(Number(activityId));

  return new Promise((resolve, reject) => {
    cl.getActivityOfS(req, getMetadata(), getOptionsOfLight(), (err, res) => {
      if (!isNull(err)) {
        reject(wrapperGrpcError(err.details));
        return;
      }
      const opRet = res.getOpRet()!;
      if (!opRet.getSuccess()) {
        reject(wrapperGrpcError(opRet.getMsg()));
        return;
      }
      resolve(activityOfSPbToObject(res.getActivityOfS()!));
    });
  });
};

export const getActivityOfSByParentIDAndSpokesmanID = async ({
  parentId,
  spokesmanId,
}: GetActivityOfSByParentIDAndSpokesmanIDParams): Promise<
  ActivityOfS | undefined
> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.GetActivityOfSByParentIDAndSpokesmanIDRequest();

  req.setParentId(Number(parentId));
  req.setSpokesmanId(Number(spokesmanId));

  return new Promise((resolve, reject) => {
    cl.getActivityOfSByParentIDAndSpokesmanID(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          if (opRet.getCode() === GrpcErrCode.NOT_FOUND) {
            resolve(undefined);
            return;
          } else {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
        }
        resolve(activityOfSPbToObject(res.getActivityOfS()!));
      }
    );
  });
};

/****************************************************************************************/
/*                                   activity helper                                    */
/****************************************************************************************/
const REG_TIMERANGE_PART = /\d{2}:[0-5]\d/g;
export const checkActivityOfBParamFields = (
  {
    type,
    intro,
    begined,
    ended,
    timeRanges,
    checkIn1,
    lottery1,
    saleMode,
    deliveryModes,
    isUseWarehouseShippingFeeRule,
    unifiedShippingFee,
    warehouseIds,
    activityProductWithSkus,
    consignment,
  }: StringIndexer,
  isCreate: boolean = true
) => {
  if (!isActivityType(type)) {
    throw Error("type invalid");
  }

  if (checkNeedTypeInfo(type)) {
    switch (type) {
      case ActivityType.CHECK_IN__1:
        if (
          isUndefined(checkIn1) ||
          !isNumber(checkIn1.awardOnceCoins) ||
          !isNumber(checkIn1.awardReachMaxCoins) ||
          !isNumber(checkIn1.continuous)
        ) {
          throw Error("type of checkIn1 invalid");
        }
        break;
      case ActivityType.LOTTERY__1:
        if (
          isUndefined(lottery1) ||
          !isString(lottery1.uiType) ||
          !isNumber(lottery1.winRate) ||
          !isArray(lottery1.prizeRates) ||
          lottery1.prizeRates.length === 0 ||
          lottery1.prizeRates.some((prizeRate) => !isNumber(prizeRate))
        ) {
          throw Error("type of lottery1 invalid");
        }
        break;
    }
  }

  if (
    !isArray(intro) ||
    // intro.length === 0 ||
    intro.some(
      (it: ActivityIntroItem) =>
        ![
          ActivityIntroItemType.TEXT,
          ActivityIntroItemType.PIC,
          ActivityIntroItemType.PIC_LIST,
          ActivityIntroItemType.VIDEO,
        ].includes(it.type) //|| isEmpty(it.resource)
    )
  ) {
    throw Error("intro invalid");
  }

  if (!isNumber(begined) || !isNumber(ended) || begined >= ended) {
    throw Error("begined or ended invalid");
  }

  if (ended - Date.now() < 5 * 60 * 1000) {
    throw Error("结束时间必须是当前时间的5分钟后起");
  }

  // timeRanges可以不传,此处正则不能用变量代替,因为每次last_index变化导致匹配失败
  if (
    !isUndefined(timeRanges) &&
    (!isArray(timeRanges) ||
      timeRanges.some((tr: TimeRange) => {
        return (
          !/\d{2}:[0-5]\d/g.test(tr.beginAt) || !/\d{2}:[0-5]\d/g.test(tr.endAt)
        );
      }))
  ) {
    throw Error("timeRanges invalid");
  }

  if (!isActivitySaleMode(saleMode)) {
    throw Error("saleMode invalid");
  }

  if (!isUndefined(deliveryModes)) {
    if (
      !isArray(deliveryModes) ||
      deliveryModes.length === 0 ||
      deliveryModes.some((mode) => !isDeliveryMode(mode))
    ) {
      throw Error("deliveryModes invalid");
    }

    if (deliveryModes.some((mode) => mode === DeliveryMode.IN_CITY)) {
      throw Error("deliveryMode in_city not imp");
    }
  } else {
    throw Error("deliveryModes empty");
  }

  if (isUseWarehouseShippingFeeRule && !isNumber(unifiedShippingFee)) {
    throw Error("unifiedShippingFee invalid");
  }

  if (!isArray(warehouseIds) || warehouseIds.length === 0) {
    throw Error("warehouseIds invalid");
  }

  if (
    !isArray(activityProductWithSkus) ||
    activityProductWithSkus.length === 0 ||
    activityProductWithSkus.some((it: ActivityProductWithSku) => {
      if (isUndefined(it.productId)) {
        return true;
      }
      if (!isArray(it.skus) || it.skus.length === 0) {
        return true;
      }

      return it.skus.some(
        (sku: ActivitySku) =>
          sku.productId !== it.productId ||
          sku.price < 0 ||
          (!isUndefined(sku.maximum) && !isInteger(sku.maximum))
      );
    })
  ) {
    throw Error("activityProductWithSkus invalid");
  }
  const productIdsOfActivity = activityProductWithSkus.map(
    (it: ActivityProductWithSku) => it.productId
  );

  if (isUndefined(consignment)) {
    if (type === ActivityType.GROUP_BUYING__1) {
      throw Error("consignment invalid");
    }
  } else {
    if (
      !consignment.allowAllSpokesman &&
      (!isArray(consignment.specificSpokesmanIds) ||
        // consignment.specificSpokesmanIds.length === 0 || ==> allowAllSpokesman = false 并且 specificSpokesmanIds=[]表示仅品牌直卖
        consignment.specificSpokesmanIds.some((v) => !isString(v)))
    ) {
      throw Error("consignment.specificSpokesmanIds invalid");
    }

    if (
      !isArray(consignment.consignmentBonusSettings) ||
      consignment.consignmentBonusSettings.some(
        (it: ActivityConsignmentBonusSetting) =>
          isUndefined(it.productId) ||
          !productIdsOfActivity.includes(it.productId) ||
          !isNumber(it.bonusRate)
      )
    ) {
      throw Error("consignment.consignmentBonusSettings invalid");
    }
  }

  console.log("activity params valid success!");
};

export const checkActivityOfStoreParamFields = (
  {
    type,
    intro,
    begined,
    ended,
    timeRanges,
    saleMode,
    activityProductWithSkus,
    consignment,
  }: StringIndexer,
  isCreate: boolean = true
) => {
  if (!isActivityType(type)) {
    throw Error("type invalid");
  }

  if (
    !isArray(intro) ||
    // intro.length === 0 ||
    intro.some(
      (it: ActivityIntroItem) =>
        ![
          ActivityIntroItemType.TEXT,
          ActivityIntroItemType.PIC,
          ActivityIntroItemType.PIC_LIST,
          ActivityIntroItemType.VIDEO,
        ].includes(it.type) //|| isEmpty(it.resource)
    )
  ) {
    throw Error("intro invalid");
  }

  if (!isNumber(begined) || !isNumber(ended) || begined >= ended) {
    throw Error("begined or ended invalid");
  }

  if (ended - Date.now() < 5 * 60 * 1000) {
    throw Error("结束时间必须是当前时间的5分钟后起");
  }

  // timeRanges可以不传,此处正则不能用变量代替,因为每次last_index变化导致匹配失败
  if (
    !isUndefined(timeRanges) &&
    (!isArray(timeRanges) ||
      timeRanges.some((tr: TimeRange) => {
        return (
          !/\d{2}:[0-5]\d/g.test(tr.beginAt) || !/\d{2}:[0-5]\d/g.test(tr.endAt)
        );
      }))
  ) {
    throw Error("timeRanges invalid");
  }

  if (!isActivitySaleMode(saleMode)) {
    throw Error("saleMode invalid");
  }

  if (
    !isArray(activityProductWithSkus) ||
    activityProductWithSkus.length === 0 ||
    activityProductWithSkus.some((it: ActivityProductWithSku) => {
      if (isUndefined(it.productId)) {
        return true;
      }
      if (!isArray(it.skus) || it.skus.length === 0) {
        return true;
      }

      return it.skus.some(
        (sku: ActivitySku) =>
          sku.productId !== it.productId ||
          sku.price < 0 ||
          (!isUndefined(sku.maximum) && !isInteger(sku.maximum))
      );
    })
  ) {
    throw Error("activityProductWithSkus invalid");
  }
  const productIdsOfActivity = activityProductWithSkus.map(
    (it: ActivityProductWithSku) => it.productId
  );

  if (isUndefined(consignment)) {
    if (type === ActivityType.GROUP_BUYING__1) {
      throw Error("consignment invalid");
    }
  } else {
    if (
      !consignment.allowAllSpokesman &&
      (!isArray(consignment.specificSpokesmanIds) ||
        // consignment.specificSpokesmanIds.length === 0 || ==> allowAllSpokesman = false 并且 specificSpokesmanIds=[]表示仅品牌直卖
        consignment.specificSpokesmanIds.some((v) => !isString(v)))
    ) {
      throw Error("consignment.specificSpokesmanIds invalid");
    }

    if (
      !isArray(consignment.consignmentBonusSettings) ||
      consignment.consignmentBonusSettings.some(
        (it: ActivityConsignmentBonusSetting) =>
          isUndefined(it.productId) ||
          !productIdsOfActivity.includes(it.productId) ||
          !isNumber(it.bonusRate)
      )
    ) {
      throw Error("consignment.consignmentBonusSettings invalid");
    }
  }

  console.log("activity params valid success!");
};

export const checkActivityOfSParamFields = (
  { endorseActivityId, activityProductIsShows }: StringIndexer,
  isCreate: boolean = true
) => {
  if (isCreate && isUndefined(endorseActivityId)) {
    throw Error("endorseActivityId invalid");
  }

  if (
    !isArray(activityProductIsShows) ||
    activityProductIsShows.length === 0 ||
    activityProductIsShows.some((it: ActivityProductIsShow) => {
      if (isUndefined(it.productId)) {
        return true;
      }
      if (!isBoolean(it.isShow)) {
        return true;
      }
    })
  ) {
    throw Error("activityProductIsShows invalid");
  }
};

/****************************************************************************************/
/*                                   activity joins entity                              */
/****************************************************************************************/

const activityItemOfBWithStatPbToObject = (
  pb: activitypb.ActivityItemOfBWithStatEntity
): ActivityItemOfBWithStat => {
  return {
    // activity
    activityId: toString(pb.getId()),
    modified: pbTimestampToJs(pb.getModified())!,
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    saleMode: pb.getSaleMode() as ActivitySaleMode,

    // activity_stat
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),
  };
};

const activityItemOfStoreWithStatPbToObject = (
  pb: activitypb.ActivityItemOfStoreWithStatEntity
): ActivityItemOfStoreWithStat => {
  return {
    // activity
    activityId: toString(pb.getId()),
    modified: pbTimestampToJs(pb.getModified())!,
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    storeId: toString(pb.getStoreId()),
    distributorId: toString(pb.getDistributorId()),
    saleMode: pb.getSaleMode() as ActivitySaleMode,

    // activity_stat
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),
  };
};

const activityItemOfSWithStatPbToObject = (
  pb: activitypb.ActivityItemOfSWithStatEntity
): ActivityItemOfSWithStat => {
  return {
    // activity
    activityId: toString(pb.getId()),
    modified: pbTimestampToJs(pb.getModified())!,
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    spokesmanId: toString(pb.getSpokesmanId()),
    // activity_stat
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),
  };
};

const activityItemOfU2BWithStatAndBrandInfoPbToObject = (
  pb: activitypb.ActivityItemOfU2BWithStatAndBrandInfoEntity
): ActivityItemOfU2BWithStatAndBrandInfo => {
  return {
    // activity
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    saleMode: pb.getSaleMode() as ActivitySaleMode,
    endorseSpokesmanId: toString(pb.getEndorseSpokesmanId()),
    endorsedActivityIds: pb.getEndorsedActivityIdsList().map(toString),
    // activity_stat
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),

    // brand info
    brandName: pb.getBrandName(),
    brandPic: pb.getBrandPic(),
  };
};

const activityOfU2CWithStatAndOwnerInfoPbToObject = (
  pb: activitypb.ActivityOfU2CWithStatAndOwnerInfoEntity
): ActivityOfU2CWithStatAndOwnerInfo => {
  return {
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    storeId: pb.getStoreId() == 0 ? undefined : toString(pb.getStoreId()),
    distributorId:
      pb.getDistributorId() == 0 ? undefined : toString(pb.getDistributorId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    background: emtpyToUndefined(pb.getBackground()),
    poster: emtpyToUndefined(pb.getPoster()),
    saleMode: pb.getSaleMode() as ActivitySaleMode,
    verifyQualification: pb.getVerifyQualification(),
    qualifyTypes: pb.getQualifyTypesList().map((v) => v as ActivityQualifyType),
    deliveryModes: pb.getDeliveryModesList().map((v) => v as DeliveryMode),
    isUseWarehouseShippingFeeRule: pb.getIsUseWarehouseShippingFeeRule(),
    unifiedShippingFee: pb.getUnifiedShippingFee(),
    spokesmanId: toString(pb.getSpokesmanId()),
    minimumPurchaseAmount: pb.getMinimumPurchaseAmount(),
    tel: pb.getTel(),
    owner: pb.getOwner() as ActivityOwner,
    ownerName: pb.getOwnerName(),
    ownerPic: pb.getOwnerPic(),
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),
    warehouses: pb.getWarehousesList().map((o) => ({
      id: toString(o.getId()),
      tel: o.getTel(),
      linkman: o.getLinkman(),
      address: o.getAddress(),
      lng: o.getLng(),
      lat: o.getLat(),
      cityCode: o.getCityCode(),
      deliveryModes: o.getDeliveryModesList().map((dm) => dm as DeliveryMode),
    })),
    activityProductWithAttributeDefAndSkus: pb
      .getActivityProductWithAttributeDefAndSkusList()
      .map(activityProductWithAttributeDefAndSkusPbToObject),
    isWxpayAvailable: pb.getIsWxpayAvailable(),
    openEndorseToUser: pb.getOpenEndorseToUser(),
    hasNotEndorsed: pb.getHasNotEndorsed(),
    isEndorsementEntranceDisplay: pb.getIsEndorsementEntranceDisplay(),
    endorseSpokesmanId: toString(pb.getEndorseSpokesmanId()),
    isDistributionEntranceDisplay: pb.getIsDistributionEntranceDisplay(),
    distributeDistributorId: toString(pb.getDistributeDistributorId()),
  };
};

const activityItemOfU2CWithStatAndOwnerInfoPbToObject = (
  pb: activitypb.ActivityItemOfU2CWithStatAndOwnerInfoEntity
): ActivityItemOfU2CWithStatAndOwnerInfo => {
  return {
    // activity
    activityId: toString(pb.getId()),
    brandId: toString(pb.getBrandId()),
    pubUserId: toString(pb.getPubUserId()),
    name: pb.getName(),
    type: pb.getType() as ActivityType,
    intro: JSON.parse(pb.getIntro()),
    processStatus: pb.getProcessStatus() as ActivityProcessStatus,
    published: pbTimestampToJs(pb.getPublished()),
    begined: pbTimestampToJs(pb.getBegined())!,
    ended: pbTimestampToJs(pb.getEnded())!,
    timeRanges: pb.getTimeRangesList().map((v) => ({
      beginAt: v.getBeginAt(),
      endAt: v.getEndAt(),
    })),
    spokesmanId: toString(pb.getSpokesmanId()),
    owner: pb.getOwner() as ActivityOwner,
    ownerName: pb.getOwnerName(),
    ownerPic: pb.getOwnerPic(),
    orderCount: pb.getOrderCount(),
    latestAccessed: pbTimestampToJs(pb.getLatestAccessed()),
    pv: pb.getPv(),
    uv: pb.getUv(),
    iv: pb.getIv(),
    // canManage: pb.getCanManage(),
    // endorseSpokesmanId: toString(pb.getEndorseSpokesmanId()),
    // openEndorseToUser: pb.getOpenEndorseToUser(),
    // hasNotEndorsed: pb.getHasNotEndorsed(),
    // isEndorsementEntranceDisplay: pb.getIsEndorsementEntranceDisplay(),
  };
};

/****************************************************************************************/
/*                                   activity joins query                               */
/****************************************************************************************/

export const getActivityOfU2CWithStatAndOwnerInfoForUser = async ({
  activityId,
  userId,
}: GetActivityOfU2CWithStatAndOwnerInfoForUserParams): Promise<ActivityOfU2CWithStatAndOwnerInfo> => {
  const cl = getBgsActivityOpSafely();
  const req =
    new activitypb.GetActivityOfU2CWithStatAndOwnerInfoForUserRequest();

  req.setId(Number(activityId));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.getActivityOfU2CWithStatAndOwnerInfoForUser(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
        }
        resolve(
          activityOfU2CWithStatAndOwnerInfoPbToObject(
            res.getActivityOfU2cWithStatAndOwnerInfo()!
          )
        );
      }
    );
  });
};

export interface ListActivityItemOfBWithStatsByBrandIDParam {
  brandId: string;
  isAll: boolean;
  processStatuses: ActivityProcessStatus[];
  keyword?: string;
}

export const listActivityItemOfBWithStatsByBrandID = async (
  {
    brandId,
    isAll,
    processStatuses,
    keyword,
  }: ListActivityItemOfBWithStatsByBrandIDParam,
  pager: PageParams
): Promise<PagedList<ActivityItemOfBWithStat>> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.ListActivityItemOfBWithStatsByBrandIDRequest();

  req.setLimit(pager.limit);
  req.setOffset(pager.offset);
  req.setTs(jsTimestampToPb(pager.ts));
  req.setBrandId(Number(brandId));
  req.setIsAll(isAll);
  req.setProcessStatusesList(processStatuses);
  if (!isUndefined(keyword)) {
    req.setKeyword(keyword);
  }

  return new Promise((resolve, reject) => {
    cl.listActivityItemOfBWithStatsByBrandID(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        const ret: PagedList<ActivityItemOfBWithStat> = {
          total: 0,
          items: [],
        };
        ret.total = res.getTotal();
        ret.items = res
          .getActivityItemOfBWithStatsList()
          .map(activityItemOfBWithStatPbToObject);
        resolve(ret);
      }
    );
  });
};

export interface ListActivityItemOfStoreWithStatsByStoreIDParam {
  storeId: string;
  isAll: boolean;
  processStatuses: ActivityProcessStatus[];
  keyword?: string;
}

export const listActivityItemOfStoreWithStatsByStoreID = async (
  {
    storeId,
    isAll,
    processStatuses,
    keyword,
  }: ListActivityItemOfStoreWithStatsByStoreIDParam,
  pager: PageParams
): Promise<PagedList<ActivityItemOfStoreWithStat>> => {
  const cl = getBgsActivityOpSafely();
  const req = new activitypb.ListActivityItemOfStoreWithStatsByStoreIDRequest();

  req.setLimit(pager.limit);
  req.setOffset(pager.offset);
  req.setTs(jsTimestampToPb(pager.ts));
  req.setStoreId(Number(storeId));
  req.setIsAll(isAll);
  req.setProcessStatusesList(processStatuses);
  if (!isUndefined(keyword)) {
    req.setKeyword(keyword);
  }

  return new Promise((resolve, reject) => {
    cl.listActivityItemOfStoreWithStatsByStoreID(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        const ret: PagedList<ActivityItemOfStoreWithStat> = {
          total: 0,
          items: [],
        };
        ret.total = res.getTotal();
        ret.items = res
          .getActivityItemOfStoreWithStatsList()
          .map(activityItemOfStoreWithStatPbToObject);
        resolve(ret);
      }
    );
  });
};

export interface ListActivityItemOfSWithStatsByUserIDAsSpokesmanParam {
  userId: string;
  isAll: boolean;
  processStatuses: ActivityProcessStatus[];
  keyword?: string;
}

export const listActivityItemOfSWithStatsByUserIDAsSpokesman = async (
  {
    userId,
    isAll,
    processStatuses,
    keyword,
  }: ListActivityItemOfSWithStatsByUserIDAsSpokesmanParam,
  pager: PageParams
): Promise<PagedList<ActivityItemOfSWithStat>> => {
  const cl = getBgsActivityOpSafely();
  const req =
    new activitypb.ListActivityItemOfSWithStatsByUserIDAsSpokesmanRequest();

  req.setLimit(pager.limit);
  req.setOffset(pager.offset);
  req.setTs(jsTimestampToPb(pager.ts));
  req.setUserId(Number(userId));
  req.setIsAll(isAll);
  req.setProcessStatusesList(processStatuses);
  if (!isUndefined(keyword)) {
    req.setKeyword(keyword);
  }

  return new Promise((resolve, reject) => {
    cl.listActivityItemOfSWithStatsByUserIDAsSpokesman(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        const ret: PagedList<ActivityItemOfSWithStat> = {
          total: 0,
          items: [],
        };
        ret.total = res.getTotal();
        ret.items = res
          .getActivityItemOfSWithStatsList()
          .map(activityItemOfSWithStatPbToObject);
        resolve(ret);
      }
    );
  });
};

export const listActivityItemOfU2BWithStatAndBrandInfosByUserID = async (
  userId: string,
  pager: PageParams
): Promise<PagedList<ActivityItemOfU2BWithStatAndBrandInfo>> => {
  const cl = getBgsActivityOpSafely();
  const req =
    new activitypb.ListActivityItemOfU2BWithStatAndBrandInfosByUserIDRequest();

  req.setLimit(pager.limit);
  req.setOffset(pager.offset);
  req.setTs(jsTimestampToPb(pager.ts));
  req.setUserId(Number(userId));

  return new Promise((resolve, reject) => {
    cl.listActivityItemOfU2BWithStatAndBrandInfosByUserID(
      req,
      getMetadata(),
      getOptionsOfLight(),
      (err, res) => {
        if (!isNull(err)) {
          reject(wrapperGrpcError(err.details));
          return;
        }
        const opRet = res.getOpRet()!;
        if (!opRet.getSuccess()) {
          reject(wrapperGrpcError(opRet.getMsg()));
          return;
        }
        const ret: PagedList<ActivityItemOfU2BWithStatAndBrandInfo> = {
          total: 0,
          items: [],
        };
        ret.total = res.getTotal();
        ret.items = res
          .getActivityItemOfU2bWithStatAndBrandInfosList()
          .map(activityItemOfU2BWithStatAndBrandInfoPbToObject);
        resolve(ret);
      }
    );
  });
};

export const listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsSpokesman =
  async (
    // forUserId: string,
    byUserId: string,
    pager: PageParams
  ): Promise<PagedList<ActivityItemOfU2CWithStatAndOwnerInfo>> => {
    const cl = getBgsActivityOpSafely();
    const req =
      new activitypb.ListActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsSpokesmanRequest();

    req.setLimit(pager.limit);
    req.setOffset(pager.offset);
    req.setTs(jsTimestampToPb(pager.ts));
    // req.setForUserId(Number(forUserId));
    req.setByUserId(Number(byUserId));

    return new Promise((resolve, reject) => {
      cl.listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsSpokesman(
        req,
        getMetadata(),
        getOptionsOfLight(),
        (err, res) => {
          if (!isNull(err)) {
            reject(wrapperGrpcError(err.details));
            return;
          }
          const opRet = res.getOpRet()!;
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
          const ret: PagedList<ActivityItemOfU2CWithStatAndOwnerInfo> = {
            total: 0,
            items: [],
          };
          ret.total = res.getTotal();
          ret.items = res
            .getActivityItemOfU2cWithStatAndOwnerInfosList()
            .map(activityItemOfU2CWithStatAndOwnerInfoPbToObject);
          resolve(ret);
        }
      );
    });
  };

export const listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsFollower =
  async (
    // forUserId: string,
    byUserId: string,
    pager: PageParams
  ): Promise<PagedList<ActivityItemOfU2CWithStatAndOwnerInfo>> => {
    const cl = getBgsActivityOpSafely();
    const req =
      new activitypb.ListActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsFollowerRequest();

    req.setLimit(pager.limit);
    req.setOffset(pager.offset);
    req.setTs(jsTimestampToPb(pager.ts));
    // req.setForUserId(Number(forUserId));
    req.setByUserId(Number(byUserId));

    return new Promise((resolve, reject) => {
      cl.listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsFollower(
        req,
        getMetadata(),
        getOptionsOfLight(),
        (err, res) => {
          if (!isNull(err)) {
            reject(wrapperGrpcError(err.details));
            return;
          }
          const opRet = res.getOpRet()!;
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
          const ret: PagedList<ActivityItemOfU2CWithStatAndOwnerInfo> = {
            total: 0,
            items: [],
          };
          ret.total = res.getTotal();
          ret.items = res
            .getActivityItemOfU2cWithStatAndOwnerInfosList()
            .map(activityItemOfU2CWithStatAndOwnerInfoPbToObject);
          resolve(ret);
        }
      );
    });
  };

export const listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsInvolver =
  async (
    userId: string,
    pager: PageParams
  ): Promise<PagedList<ActivityItemOfU2CWithStatAndOwnerInfo>> => {
    const cl = getBgsActivityOpSafely();
    const req =
      new activitypb.ListActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsInvolverRequest();

    req.setLimit(pager.limit);
    req.setOffset(pager.offset);
    req.setTs(jsTimestampToPb(pager.ts));
    req.setUserId(Number(userId));

    return new Promise((resolve, reject) => {
      cl.listActivityItemOfU2CWithStatAndOwnerInfosForUserByUserIDAsInvolver(
        req,
        getMetadata(),
        getOptionsOfLight(),
        (err, res) => {
          if (!isNull(err)) {
            reject(wrapperGrpcError(err.details));
            return;
          }
          const opRet = res.getOpRet()!;
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
          const ret: PagedList<ActivityItemOfU2CWithStatAndOwnerInfo> = {
            total: 0,
            items: [],
          };
          ret.total = res.getTotal();
          ret.items = res
            .getActivityItemOfU2cWithStatAndOwnerInfosList()
            .map(activityItemOfU2CWithStatAndOwnerInfoPbToObject);
          resolve(ret);
        }
      );
    });
  };

export interface ListActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwnParam {
  brandId: string;
  dateBegin: number;
  dateEnd: number;
}

export const listActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwn =
  async (
    {
      // userId: string,
      brandId,
      dateBegin,
      dateEnd,
    }: ListActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwnParam,
    pager: PageParams
  ): Promise<PagedList<ActivityItemOfU2CWithStatAndOwnerInfo>> => {
    const cl = getBgsActivityOpSafely();
    const req =
      new activitypb.ListActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwnRequest();

    console.log("dateBegin:", dateBegin);
    console.log("dateEnd:", dateEnd);
    req.setLimit(pager.limit);
    req.setOffset(pager.offset);
    req.setTs(jsTimestampToPb(pager.ts));
    // req.setUserId(Number(userId));
    req.setBrandId(Number(brandId));
    req.setDateBegin(jsTimestampToPb(dateBegin));
    req.setDateEnd(jsTimestampToPb(dateEnd));

    return new Promise((resolve, reject) => {
      cl.listActivityItemOfU2CWithStatAndOwnerInfosForUserByBrandIDInBrandOwn(
        req,
        getMetadata(),
        getOptionsOfLight(),
        (err, res) => {
          if (!isNull(err)) {
            reject(wrapperGrpcError(err.details));
            return;
          }
          const opRet = res.getOpRet()!;
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
          const ret: PagedList<ActivityItemOfU2CWithStatAndOwnerInfo> = {
            total: 0,
            items: [],
          };
          ret.total = res.getTotal();
          ret.items = res
            .getActivityItemOfU2cWithStatAndOwnerInfosList()
            .map(activityItemOfU2CWithStatAndOwnerInfoPbToObject);
          resolve(ret);
        }
      );
    });
  };

export interface ListActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwnParam {
  storeId: string;
  dateBegin: number;
  dateEnd: number;
}

export const listActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwn =
  async (
    {
      // userId: string,
      storeId,
      dateBegin,
      dateEnd,
    }: ListActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwnParam,
    pager: PageParams
  ): Promise<PagedList<ActivityItemOfU2CWithStatAndOwnerInfo>> => {
    const cl = getBgsActivityOpSafely();
    const req =
      new activitypb.ListActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwnRequest();

    req.setLimit(pager.limit);
    req.setOffset(pager.offset);
    req.setTs(jsTimestampToPb(pager.ts));
    // req.setUserId(Number(userId));
    req.setStoreId(Number(storeId));
    req.setDateBegin(jsTimestampToPb(dateBegin));
    req.setDateEnd(jsTimestampToPb(dateEnd));

    return new Promise((resolve, reject) => {
      cl.listActivityItemOfU2CWithStatAndOwnerInfosForUserByStoreIDInStoreOwn(
        req,
        getMetadata(),
        getOptionsOfLight(),
        (err, res) => {
          if (!isNull(err)) {
            reject(wrapperGrpcError(err.details));
            return;
          }
          const opRet = res.getOpRet()!;
          if (!opRet.getSuccess()) {
            reject(wrapperGrpcError(opRet.getMsg()));
            return;
          }
          const ret: PagedList<ActivityItemOfU2CWithStatAndOwnerInfo> = {
            total: 0,
            items: [],
          };
          ret.total = res.getTotal();
          ret.items = res
            .getActivityItemOfU2cWithStatAndOwnerInfosList()
            .map(activityItemOfU2CWithStatAndOwnerInfoPbToObject);
          resolve(ret);
        }
      );
    });
  };
